#!/usr/bin/env python
import gameworld
import events.dispatcher
import pygame
import random

class Game(object):
    def __init__(self):
        self.clock = pygame.time.Clock()
        self.running = True
        self.paused = False
    
    def setup(self):
         # Initialise screen
        pygame.init()
        random.seed()
        
        #Register for events
        events.dispatcher.instance().register( events.dispatcher.PyGameQuit, self.onQuit )
        
        
    def onQuit(self, _):
        self.running = False

    
    def run( self ):

        # Main loop
        while self.running:
            self._loop()
            pygame.display.flip()

    def _loop(self):
        dt = float( self.clock.tick( 30 ) ) / float(1000) #convert to seconds
        if self.paused:
            dt = 0.0


        events.dispatcher.instance().update( dt )
        entities = gameworld.instance().getEntities()

        for e in entities:
            e.update(dt)

        self._preRender()
        for e in entities:
            e.draw( )
        self._postRender()

    def _preRender(self):
        pass

    def _postRender(self):
        pass

    def destroy(self):
        pygame.display.quit()